package com.foreknow.elm.test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 创建Servlet
 * 1. 所有的类都要继承HttpServlet
 * 2. 重写doGet/doPost方法
 *      如果客户端向服务器端发送的是get请求 那么就自动调用doGet()方法
 *      如果客户端向服务器端发送的是post请求 那么就自动调用doPost()方法
 */
//@WebServlet(urlPatterns="/hello")
public class FirstServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求信息的字符编码（必须在使用request之前进行设置）
        req.setCharacterEncoding("utf-8");
        //使客户端浏览器并根据不同的MIME调用浏览器内不同的程序嵌入模块来处理相应的数据。
        resp.setContentType("text/html;charset=utf-8");
        //设置响应信息的字符编码（必须在创建响应输出流之前进行设置）
        resp.setCharacterEncoding("utf-8");
        String name = req.getParameter("name");
        //向网页输出内容
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset=\"utf-8\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>"+name +"</h1>");
        out.println("</body>");
        out.flush(); //刷新
        out.close(); //关闭流

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
